﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
//using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using App.Core.Extensions;
using App.Data;

public partial class Pages_Public_Login : BasePage
{    

    //protected override void OnPreInit(EventArgs e)
    //{
    //    if (WebUtil.IsMobileRequest())
    //        this.MasterPageFile = "~/MregN/Registration.master";
    //    base.OnPreInit(e);
    //}
    protected void Page_Load(object sender, EventArgs e)
    {        
        BindPageInfo();
        if (!IsPostBack)
        {            
            ChangeUIForMobile();

            if (String.Compare(Request[AppConstants.QueryString.LOG_OUT], "True", true) == 0)            
                base.SignoutUser();            
            else if (SessionCache.CurrentUser != null)            
                FormsAuthenticationUtil.RedirectFromLoginPage(SessionCache.CurrentUser.LoginName, SessionCache.CurrentUser.UserGroup.Name, true);
            
            //String returnUrl = WebUtil.GetQueryStringValueInString("ReturnUrl");
            //if (WebUtil.IsMobileRequest() && returnUrl.IsNullOrEmpty())
            //{
            //    Response.Redirect("/MregN/default.aspx");
            //    return;
            //}
            txtUserName.Focus();            
        }
    }
    protected void BindPageInfo()
    {
        Page.Title = WebUtil.GetPageTitle("User Log In");        
    }
    protected void ChangeUIForMobile()
    {
        if (WebUtil.IsMobileRequest())
        {
            divLeftColumn.Visible = false;
            divRightColumn.Attributes["class"] = String.Empty;
            divRightColumn.Attributes["style"] = String.Empty;
        }
    }
    protected void LoginButton_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            if (SessionCache.FailedLoginAttemptCount >= 4)
            {
                SessionCache.NotificationMessage = "Repeated multiple attempts have been made trying to access this site.";
                Response.Redirect(AppConstants.Pages.SHOW_MESSAGE, false);
                return;
            }
            String userName = txtUserName.Text;
            String password = txtPassword.Text;
            //userName = ReplaceBadWords(userName);

            BtcHousingEntities context = new BtcHousingEntities();
            //AdminSystemUser user = userDAO.GetByUserNamePassword(userName, password);
            User user = context.Users.FirstOrDefault(P => String.Compare(P.LoginName, userName, false) == 0 && String.Compare(P.Password, password, false) == 0);   
            LoginUser(user, userName, chkRememberMe.Checked);            
        }
    }

    /// <summary>
    /// Logs In a User to the web site and redirects to the desired page.
    /// </summary>
    /// <param name="user"></param>
    /// <param name="userName"></param>
    /// <param name="rememberMe"></param>
    protected void LoginUser(User user, String userName, bool rememberMe)
    {
        if (user == null) //Login Failed
        {
            //SessionCache.AttemptedUserName = userName;
            SessionCache.FailedLoginAttemptCount = SessionCache.FailedLoginAttemptCount + 1;
            WebUtil.ShowMessageBox(divErrorMessage, "Login Failed. Check your User Name, Password and try again.", true);            
        }
        else 
        {
            ///Check the User is Active or Inactive
            if (!user.IsActive)
            {
                String message = @"Your login information is valid, however your account has been disabled.";
                //divErrorMessage.Style["height"] = "70px;";
                WebUtil.ShowMessageBox(divErrorMessage, message, true);
                SessionCache.FailedLoginAttemptCount = SessionCache.FailedLoginAttemptCount + 1;
                //SessionCache.AttemptedUserName = userName;
                return;
            }
            //String groupName = "Administrator";
            ///Load Group and Group Permissions
            //if (String.Compare(user.UserID, "Admin", true) != 0)
            //{                
            //    AdminGroupTableDAO groupDAO = new AdminGroupTableDAO();
            //    user.Group = groupDAO.Get(user.GroupCode);                
            //    groupName = user.Group.GroupName;
            //}
            SessionCache.CurrentUser = user;
            ///After Successfull Login Redirect to the Requested Page
            //System.Web.Security.FormsAuthentication.RedirectFromLoginPage(user.UserLogInName, rememberMe);
            FormsAuthenticationUtil.RedirectFromLoginPage(user.LoginName, user.UserGroup.Name, rememberMe);   
        }
    }
    protected void LogOutUser()
    {
        //FormsAuthentication.SignOut();
        //SessionCache.ClearSession();

        //Response.Cookies[AppConstants.Cookie.BASE].Expires = DateTime.Now.AddYears(-100);
    }    
}
